<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member_Model extends CI_Model {
	
	public function __construct() {
		$this->db->cache_delete_all();
		$this->load->helper("public");
		$this->load->helper("ip_helper");

		ini_set("display_errors", "On"); 
        error_reporting(E_ALL | E_STRICT);
	}
	//从member表中通过1一个字段取一条记录
	public function select_one_by_field($field, $value) {
        $this->db->select('*');
        $this->db->where($field, $value);
        $this->db->from('member');
 
        $query = $this->db->get();
 
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return FALSE;
        }
    }

    //新增一个用户，返回插入后的passid，用于用户注册
    public function insert_member($result) {
        $this->db->insert('member', $result);
        $passid = $this->db->insert_id();
        if (empty($passid)) {
            return FALSE;
        }
 
        return $passid;
    }
    //根据email 修改某个用户的密码
    public function changePassword($email, $newpassword) {
    	if ($this->select_one_by_field("email", $email) == FALSE) {
    		return false;
    	}
        $data = array(
            "password" => $newpassword
            );
        $this->db->where("email", $email);
        if ($this->db->update("member", $data)) {
            return true;
        } else {
            return false;
        }
    }

    //判断用户登录失败的次数是否太多
    public function isFailedTooMuch($passid) {
        $this->db->select('*');
        $this->db->where('passid', $passid);
        $this->db->from('member_failedlogin');
 
        $query = $this->db->get();
 
        if ($query->num_rows() > 0) {
            $result = $query->row_array();
 
            if ($result['lasttime'] < strtotime(date('Y-m-d')) ) {
                $data = array(
                    'times' => 0,
                    'lasttime' => strtotime(date('Y-m-d'))
                    );
                $this->db->where('passid', $passid);
                $this->db->update('member_failedlogin', $data);
                return FALSE;
            }
 
            if ($result['times'] >= $this->config->item('maxFailedTimes')) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    
    //给指定用户的错误登录次数+1
    public function add_failedlogin_times($passid) {
    	//需要添加false，防止被转义
        $this->db->set('times', 'times + 1', FALSE);
        $this->db->where('passid', $passid);
        $this->db->update('member_failedlogin');
        $query = $this->db->get_where('member_failedlogin', array('passid' => $passid));
        $result = $query->row_array();
        return $this->config->item('maxFailedTimes') - intval($result['times']);
    }
     /*
    判断来源ip是否在被禁的表中
     */
    public function check_ip_banned($passid, $ip) {
        $gmt_expired = time() - $this->config->item("ip_expired");
        $this->db->select("*");
        $this->db->where("ip", $ip);
        $this->db->where("pass_id", $passid);
        $this->db->where("gmt_banned >=", $gmt_expired);
        $query = $this->db->get("member_ipbanned");
 
        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
    //获取某用户用某个ip登录错误的次数
    public function get_last_login_fails($passid, $ip) {
        $gmt_violence = time() - intval($this->config->item("gmt_violence"));
 
        $this->db->select("*");
        $this->db->where("pass_id", $passid);
        $this->db->where("ip", $ip);
        $this->db->where("gmt_login >=", $gmt_violence);
        $this->db->where("success", 1);
        $this->db->order_by("gmt_login", "desc");
        $query = $this->db->get("member_log");
 
        if ($query->num_rows() > 0) {
            $result = $query->row_array();
            $gmt_last_success = $result["gmt_login"];
        } else {
            $gmt_last_success = $gmt_violence;
        }
 
 
        $sql = "SELECT count(*) AS `failedTimes` FROM `pass_member_log` WHERE `pass_id` = ? AND `gmt_login` > ? AND `success` = '0'";
        $query = $this->db->query($sql, array($passid, $gmt_last_success));
        return $query->row_array();;
    }
    /*
    登录日志插入，包括失败和成功，默认插入成功的
     */
    public function insert_log($passid, $ip, $success = "1") {
        $data = array(
            "pass_id"   => $passid,
            "ip"        => $ip,
            "gmt_login" => time(),
            "success"   => $success
            );
        return $this->db->insert("member_log", $data);
    }

    //将某个ip禁止掉
    public function insert_ipbanned($passid, $ip){
        $data = array(
            "pass_id"    => $passid,
            "ip"         => $ip,
            "gmt_banned" => time()
            );
        return $this->db->insert("member_ipbanned", $data);
    }
    /**
     * [update_member_status 更新用户的登陆次数登陆时间等]
     * @param  [type] $passid [description]
     * @return [type]         [description]
     */
    public function update_member_status($passid) {
        $this->load->helper('ip');
        //需要添加false，防止被转义
        $this->db->set('logintimes', 'logintimes + 1', FALSE);
        $this->db->set('lastlogintime', time());
        $this->db->set('lastloginip', get_client_ip());
        $this->db->where('passid', $passid);
        $this->db->update('member_status');
    }

    //获取用户的默认角色，如果first==0，那么返回用户的第一个角色即可
    //first==0的情况适合用于，用户有N个角色，但没有一个角色isdefault为1（刚转换数据的时候会有）
    public function get_default_role($passid, $first = 0) {
        $this->db->select('*');
        $this->db->where('pass_id', $passid);
        $this->db->where('isdefault', 1);
 
        $query = $this->db->get('member_role');
 
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            if ($first == 0) {
                return false;
            } else {
                $this->db->select('*');
                $this->db->where('pass_id', $passid);
 
                $query = $this->db->get('member_role');
 
                if ($query->num_rows() > 0) {
                    return $query->row_array();
                } else {
                    return false;
                }
            }
 
        }
    }

    //设置某个用户的默认角色
    public function set_default_role($passid, $roleID, $isOnlyOneRole = 0){
        if ($isOnlyOneRole == 1) {
            $this->db->select("*");
            $this->db->where("pass_id", $passid);
            $query = $this->db->get("member_role");
            if ($query->num_rows() == 1) {
                $d = array(
                    "isdefault" => "1"
                    );
                $this->db->where("pass_id", $passid);
                return $this->db->update("member_role", $d);
            }
        } else {
            $data = array(
                "isdefault" => "0"
                );
            $this->db->where("pass_id", $passid);
            $this->db->where("isdefault", "1");
            $this->db->update("member_role", $data);
 
            $data = array(
                "isdefault" => "1"
                );
            $this->db->where("pass_id", $passid);
            $this->db->where("id", $roleID);
            return $this->db->update("member_role", $data);
        }
 
    }
    // 修改论坛角色密码
    public function changeRolePassword($uc_id, $newPassword) {
        $uc_id = intval($uc_id);
        if (empty($uc_id)) {
            log_message("error", "changRolePassword，uc_id整化后为空");
            return false;
        }
        $this->db->where("uc_id", $uc_id);
        $r["uc_password"] = authcode($newPassword, "ENCODE", $this->config->item("password_encode_key"));
        return $this->db->update("member_role", $r);
    }
    //获取用户角色数量
    public function get_roles_num($passid) {
        $this->db->select('*');
        $this->db->where('pass_id', $passid);
        $query = $this->db->get('member_role');
 
        return $query->num_rows();
    }

    //创建一个论坛角色
    public function create_role($roledata) {
        $this->db->insert('member_role', $roledata);
        return $this->db->insert_id();
    }

    //根据passid 提取出对应的所有论坛角色
    public function get_roles($passid) {
        $this->db->select('*');
        $this->db->where('pass_id', $passid);
        $query = $this->db->get('member_role');
 
        if ($query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return false;
        }
    }

    //获取用户实名资料（一般适用于研究生，研究生资料不能从实名接口中获取
    public function get_autonym($idnumber) {
        $this->db->select("*");
        $this->db->where("idnumber", $idnumber);
        $this->db->from('member_autonym');
 
        $query = $this->db->get();
 
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return FALSE;
        }
    }

    //获取用户资料，比如姓名性别等
    public function get_profile($passid) {
        $this->db->select('*');
        $this->db->where('passid', $passid);
        //$this->db->where('realname', $realname);
        $this->db->from('member_profile');
 
        $query = $this->db->get();
 
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return FALSE;
        }
    }

    //插入一条用户资料
    public function insert_profile($result) {
        $data =array(
            'realname' => $result['user_name'],
            'idcard'   => $result['user_id'],
            'company'  => $result['user_depart'],
            'isused'   => 1
            );
        if (!empty($result['user_birth'])) {
            $timestamp = strtotime($result['user_birth']);
            $data['birthyear'] = date('Y', $timestamp);
            $data['birthmonth'] = date('m', $timestamp);
            $data['birthday'] = date('d', $timestamp);
        }
 
        $this->db->insert('member_profile', $data);
        return $this->db->insert_id();
    }

    //清空用户错误登录次数
    public function clear_login_failed($passid) {
        $ths->db->set("times", "0");
        $this->db->where("passid", $passid);
        return $this->db->update("member_failedlogin");
    }

    //绑定图书馆账号
    public function bind_lib_account($stuID, $password) {
        $this->db->select("*");
        $this->db->where("idnumber", $stuID);
        $query = $this->db->get("member_libaccount");
 
        if ($query->num_rows() > 0) {
            $this->db->set("password", $password);
            $this->db->where("idnumber", $stuID);
            return $this->db->update("member_libaccount");
        } else {
            $data = array(
                "idnumber" => $stuID,
                "password" => $password,
                "gmt_update" => time(),
                "logintimes" => 0
                );
            return $this->db->insert('member_libaccount', $data);
        }
    }

    //提取passid 对应的图书馆密码
    public function get_lib_password($idnumber) {
        $this->db->select("*");
        $this->db->where("idnumber", $idnumber);
        $query = $this->db->get("member_libaccount");
 
        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return FALSE;
        }
    }

    public function send_mail($passid, $mail, $url = ""){
        $salt = getRandomString();
        $data = array(
            "passid"   => $passid,
            "mail"     => $mail,
            "salt"     => $salt,
            "gmt_post" => time(),
            "status"   => 0,
            "type" => 1
            );
        if (!$this->db->insert("member_mailcheck", $data)) {
            return false;
        }
        $s = $passid."_".md5($salt.$passid.$salt);
        $token = authcode($s, "ENCODE", $this->config->item("password_encode_key"));
        $url = site_url("user/checkmail?token=".base64_encode($token)."&url=".urlencode($url));
        //$url = site_url("user/checkmail?token=".base64_encode($token)); 
        $this->email->from('redhome@hdu.edu.cn', '红色家园');
        $this->email->to($mail); 
        $this->email->subject("请激活您的红色家园账户");
        $this->email->message("<h3>亲爱的" . $mail . ":</h3><p>感谢您注册红色家园账户! 请点击链接完成注册：</p><p><a href=\"".$url."\">点此验证红色家园账户</a>（本链接24小时内有效）</p><p></p><p>如果上述文字点击无效，请把下面网页地址复制到浏览器地址栏中打开：</p><p>" . $url . "</p><p>如果您没有申请注册红色家园账户，请忽略此邮件。</p><p>红色家园</p><p>" . date('Y-m-d') . "</p><p>（本邮件由系统自动发出，请勿回复。）</p>"); 
 
        if (!$this->email->send()) {
            //$this->email->print_debugger();
            return false;
        } else {
            return true;
        }
    }


    public function send_mail_resetpassword($email) {
        $salt = getRandomString();
        $data = array(
            "passid" => 0,
            "mail" => $email,
            "salt" => $salt,
            "gmt_post" => time(),
            "status" => 0,
            "type" => 2
            );
        if (!$this->db->insert("member_mailcheck", $data)) {
            return false;
        }
        $s = $email."_".md5($salt.$email.$salt);
        $token = authcode($s, "ENCODE", $this->config->item("password_encode_key"));
        $url = site_url("user/check_resetpassword?token=".base64_encode($token));
        $this->email->from('redhome@hdu.edu.cn', '红色家园');
        $this->email->to($email); 
        $this->email->subject("请重置您的密码");
        $this->email->message("<h3>亲爱的" . $email . ":</h3><p>请点击链接进行重置密码：</p><p><a href=\"".$url."\">点此重置家园账户密码</a>（本链接24小时内有效）</p><p></p><p>如果上述文字点击无效，请把下面网页地址复制到浏览器地址栏中打开：</p><p>" . $url . "</p><p>如果您没有申请注册红色家园账户，请忽略此邮件。</p><p>红色家园</p><p>" . date('Y-m-d') . "</p><p>（本邮件由系统自动发出，请勿回复。）</p>"); 
 
        if (!$this->email->send()) {
            //$this->email->print_debugger();
            return false;
        } else {
            return true;
        }
    }

    //检查重置密码邮件中的链接所带参数的正确性
    public function check_repassword($email, $key){
    	//首先查找日期最近的邮件发送记录
        $this->db->select("*");
        $this->db->where("mail", $email);
        $this->db->where("type", 2); //type为1 的邮件是激活邮箱的邮件
        $this->db->order_by("gmt_post", "DESC");
        $query = $this->db->get("member_mailcheck");
 
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            //status为0表明发送的邮件还没有被验证过
            if ($row["status"] != 0) {
                return false;
            }
        } else {
            log_message("error", "重置密码：没有查找到重置密码邮件发送记录");
            return false;
        }
        if ((intval(time()) - intval($row["gmt_post"])) >= intval($this->config->item("mail_expire"))) {
            log_message("error", "邮件激活：链接过期");
            return false;
        }
        $s =  md5($row["salt"].$email.$row["salt"]);
        if ($key != $s) {
            $row["status"] = 1;
            $this->db->where("id", $row["id"]);
            $this->db->update("member_mailcheck", $row);
            log_message("error", "邮件激活：token不正确");
            return false;
        } else {
            $data["status"] = 3;
            $this->db->where("id", $row["id"]);
            $this->db->update("member_mailcheck", $data);
            return true;
        }
    }

    //检查邮箱激活邮件中的链接所带参数的正确性
    public function check_email($passid, $token){
        $this->db->select("*");
        $this->db->where("passid", $passid);
        $this->db->where("type", 1);
        $this->db->order_by("gmt_post", "DESC");
        $query = $this->db->get("member_mailcheck");
 
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            if ($row["status"] != 0) {
                return false;
            }
        } else {
            log_message("error", "邮件激活：没有查找到邮件激活记录");
            return false;
        }
 
        if ((intval(time()) - intval($row["gmt_post"])) >= intval($this->config->item("mail_expire"))) {
            log_message("error", "邮件激活：链接过期");
            return false;
        }
        $s =  md5($row["salt"].$passid.$row["salt"]);
        if ($token != $s) {
            $row["status"] = 1;
            $this->db->where("id", $row["id"]);
            $this->db->update("member_mailcheck", $row);
            log_message("error", "邮件激活：token不正确");
            return false;
        } else {
            $data["status"] = 3;
            $this->db->where("id", $row["id"]);
            $this->db->update("member_mailcheck", $data);
            $data = array();
            $this->db->where("id", $passid);
            $data = array(
                "email" => $row["mail"],
                "emailstatus" => "1"
                );
            if (!$this->db->update("member", $data)) {
                log_message("error", "邮箱激活：修改member失败");
                return false;
            } else {
                return true;
            }
        }
    }

    //选择没有被验证过的最新的邮件发送记录
    public function selectNotCheckMail($passid) {
        $this->db->select("*");
        $this->db->where("passid", $passid);
        $this->db->order_by("gmt_post", "DESC");
        $query = $this->db->get("member_mailcheck");
 
        if ($query->num_rows() > 0) {
            $result = $query->row_array();
            if ($result["status"] == 0) {
                return $result;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    public function selectFromTable($table, $field, $id) {
        $this->db->select("*");
        $this->db->where($field, $id);
        $this->db->from($table);

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->row_array();
        } else {
            return FALSE;
        }
    }
    //选择出所有的应用绑定情况
    public function selectAllApps() {
        $query = $this->db->get("member_app");

        if ($query->num_rows() > 0) {
            return $query->result_array();
        } else {
            return false;
        }
    }

    public function selectAllUseApps($passid) {
        $passid = intval($passid);
        $this->db->select("member_app.id");
        $this->db->from("member_app");
        $this->db->join("member_app_bindlog", 'member_app.id = member_app_bindlog.appid', 'left');
        //$this->db->where("member_app_bindlog.passid", $_SESSION["passid"]);
        $this->db->where("member_app_bindlog.passid", $passid);
        $query = $this->db->get();
 
        if ($query->num_rows() > 0) {
            $result =  $query->result_array();
            foreach ($result as $key => $value) {
                # code...
                $appids[] = $value["id"];
            }
            $allApps = $this->selectAllApps();
            if (!empty($allApps)) {
                foreach ($allApps as $key => $value) {
                    # code...
                    if (in_array($value["id"], $appids)) {
                        $allApps[$key]["isBind"] = 1;
                    } else {
                        $allApps[$key]["isBind"] = 0;
                    }
                }
                return $allApps;
            } else {
                return false;
            }
        } else {
            $allApps = $this->selectAllApps();
            foreach ($allApps as $key => $value) {
                $allApps[$key]["isBind"] = 0;
            }
            return $allApps;
        }
    }

    public function bindApp($appid, $passid, $stuID = "", $username = "", $email = "", $password = "") {
        $this->db->select("*");
        $this->db->where("id", $appid);
        $this->db->from("member_app");
        $query = $this->db->get();

        if ($query->num_rows() == 0) {
            return array(-1, "appid 不存在");
        }

        $this->db->select("*");
        $this->db->where("id", $passid);
        $this->db->from("member");
        $query = $this->db->get();

        if ($query->num_rows() == 0) {
            return array(-3, "passid不存在");
        }

        $member = $query->row_array();

        if (empty($member["idnumber"])) {
            if ($appid == 1) {
                unset($data);
                $data = array("idnumber" => $stuID);
                $this->db->where("id", $passid);
                $this->db->update("member", $data);
            } else {
                return array(-4, "学号为空，请先绑定教务系统");
            }
        } else {
            if ($member["idnumber"] != $stuID) {
                return array(-5, "学号与注册时输入的密码不符合");
            }
        }

        $this->db->select("*");
        $this->db->where("appid", $appid);
        $this->db->where("passid", $passid);
        $this->db->from("member_app_bindlog");
        $query = $this->db->get();

        if ($query->num_rows() > 0 ) {
            $r = $query->row_array();
            $data = array(
                "username" => $username,
                "email" => $email,
                "password" => $password
                );
            $this->db->where("id", $r["id"]);
            if ($this->db->update("member_app_bindlog", $data)) {
                return array(1, "绑定成功");
            } else {
                return array(-1, "绑定不成功");
            }

        } else {
            $data = array(
                "appid" => $appid,
                "passid" => $passid,
                "username" => $username,
                "email" => $email,
                "password" => $password
                );

            if (!$this->db->insert("member_app_bindlog", $data)) {
                return array(-2, "member_app_bindlog插入失败");
            }

            return array(1, "绑定成功");
        }
   }

   public function deBind($appid, $passid) {
        $this->db->select("*");
        $this->db->where("id", $appid);
        $this->db->from("member_app");
        $query = $this->db->get();

        if ($query->num_rows() == 0) {
            return array(-1, "appid 不存在");
        }

        $this->db->select("*");
        $this->db->where("appid", $appid);
        $this->db->where("passid", $passid);
        $this->db->from("member_app_bindlog");
        $query = $this->db->get();

        if ($query->num_rows() == 0) {
            return array(-2, "绑定记录不存在");
        }

        $this->db->where("appid", $appid);
        $this->db->where("passid", $passid);
        if (!$this->db->delete("member_app_bindlog")) {
            return array(-3, "数据库出错");
        } else {
            return array(1, "解除绑定成功");
        }
   }

/**********************************可能以下代码是没有用的 **************************/
    //检查旧的密码，应该不会用到了。
    public function check_old_passport($username, $password){
        $user = $this->select_user_from_old($username);
 
        if (empty($user)) {
            return false;
        } else {
            if ($password == $user["password"]) {
                return $user;
            } else {
                return false;
            }
        }
    }

    /*
        修改member表中的password
        如果密码一样，就不进行修改。
     */
    public function update_password($passid, $password) {
        //这部分已经放在login中，可以避免多次重复查询
        /*$this->db->select("*");
        $this->db->where("id", $passid);
        $query = $this->db->get("member");
 
        if ($query->num_rows() < 0){
            return false;
        }
        $row = $query->row_array();
        //如果密码是一样的，则直接返回true，无需继续修改
        if (authcode($row["password"], "DECODE", $this->config->item("password_encode_key")) == $password) {
            return true;
        }*/
 
        $encodedPassword = authcode($password, "ENCODE", $this->config->item("password_encode_key"));
 
        $data = array(
            "password" => $encodedPassword
            );
        $this->db->where("id", $passid);
        return $this->db->update("member", $data);
    }


}